package org.foundation.jala.softzip;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.lang.reflect.Array;
import java.util.ArrayList;

import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;

public class PrincipalView extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final String SEPARATOR = System.getProperty("file.separator");
	private final char BACKSLASH = 92;
	public JMenuBar menuBar;
	public JMenu fileMenu;
	public JMenuItem openArchiveItem;
	public JFileChooser fileChooser;
	public String selectedFilePath;
	JScrollPane treeScrollPane;
	ArrayList<String> pathList;

	public PrincipalView() {
		initComponents();
	}

	private void initComponents() {

		try {
			JFrame.setDefaultLookAndFeelDecorated(true);
			JDialog.setDefaultLookAndFeelDecorated(true);
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		setMenuBarComponents();
		setButtonsPanel();
		setTreeView();
		this.setTitle("SoftZip");
		this.setSize(new Dimension(800, 600));
		this.setLocationRelativeTo(null);
		this.setResizable(false);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);

	}

	void setMenuBarComponents() {
		pathList = new ArrayList<String>();
		fileChooser = new JFileChooser();
		openArchiveItem = new JMenuItem(new AbstractAction("Open archive") {

			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void actionPerformed(ActionEvent arg0) {
				pathList = new ArrayList<String>();
				fileChooser.showOpenDialog(menuBar);
				File selectedFile = fileChooser.getSelectedFile();
				System.out.println(fileChooser.getSelectedFile()
						.getAbsolutePath());
				String rootNodeName = selectedFile.getName() + BACKSLASH;
				ArrayList<String> pathListOfSelectedFile = navigateFile(
						selectedFile, rootNodeName);
				setTreeView(pathListOfSelectedFile, rootNodeName);
				treeScrollPane.repaint();
			}
		});
		fileMenu = new JMenu("File");
		fileMenu.add(openArchiveItem);
		menuBar = new JMenuBar();
		menuBar.add(fileMenu);
		this.setJMenuBar(menuBar);
	}

	void setButtonsPanel() {
		JPanel buttonsPanel = new JPanel();
		fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		ImageIcon compressIcon = new ImageIcon("resources/compressIcon.jpg") ;
		ImageIcon decompressIcon = new ImageIcon("resources/decompressIcon.jpg");

		JButton compressButton = new JButton(new AbstractAction() {

			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void actionPerformed(ActionEvent e) {

				new DialogToChoose("Compress");
			}
		});

		JButton decompressButton = new JButton(new AbstractAction() {

			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void actionPerformed(ActionEvent e) {

				new DialogToChoose("Decompress");
			}
		});
		
		compressButton.setIcon(compressIcon);
		decompressButton.setIcon(decompressIcon);
		buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));
		buttonsPanel.add(compressButton);
		buttonsPanel.add(decompressButton);
		
		
		this.add(buttonsPanel, BorderLayout.NORTH);
	}

	private void setTreeView(ArrayList<String> paths, String rootName) {
		DefaultMutableTreeNode root = new DefaultMutableTreeNode(rootName);
		DefaultTreeModel model = new DefaultTreeModel(root);
		JTree tree = new JTree(model);
		DefaultMutableTreeNode actualNode;
		DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) model
				.getRoot();
		for (int i = 0; i < paths.size(); i++) {
			String nodeName = paths.get(i);
			actualNode = new DefaultMutableTreeNode(nodeName);
			int nodeLevel = countNodeLevel(nodeName);
			if (nodeLevel == 1) {
				model.insertNodeInto(actualNode, root, root.getChildCount());
				parentNode = actualNode;
			} else {
				int parentNodeLevel =countNodeLevel(parentNode.toString());	
                nodeName = paths.get(i);
				actualNode = new DefaultMutableTreeNode(nodeName);
				model.insertNodeInto(actualNode, parentNode,
						parentNode.getChildCount());
				if ((!getNodeName(nodeName).contains("."))) {
					if(parentNodeLevel<=nodeLevel){
					parentNode = actualNode;
					}
				}

			}
		}

		// for (int j = 1; j <= nodeLevelCounter; j++) {
		// for (String node : paths) {
		// if (countNodeLevel(node) == j) {
		// if (j == 1) {
		// actualNode = new DefaultMutableTreeNode(node);
		// model.insertNodeInto(actualNode, root,
		// parentNode.getChildCount());
		// } else {
		//
		// }
		// }
		// }
		//
		// }

		treeScrollPane.setViewportView(tree);
		treeScrollPane.updateUI();
	}

	private String getNodeName(String nodeName) {
		String name = "";
		String invName = "";
		for (int i = nodeName.length() - 1; i > 0; i--) {
			if (nodeName.charAt(i) != BACKSLASH) {
				name += (nodeName.charAt(i));
			} else {
				break;
			}
		}
		for (int j = name.length() - 1; j >= 0; j--)
			invName = invName + name.charAt(j);
		return invName;
	}

	private String getParentNodeName(String nodeName) {
		String parentName = "";
		String childNodeName = getNodeName(nodeName);
		parentName = nodeName.replaceAll(childNodeName, "");
		return parentName;
	}

	private int countNodeLevels(ArrayList<String> nodesList) {
		int levelCounter = 0;
		int currentCounter = 0;
		for (String string : nodesList) {
			currentCounter = 0;
			for (int i = 0; i < string.length() - 1; i++) {
				if (string.charAt(i) == BACKSLASH)
					currentCounter++;
				levelCounter = Math.max(levelCounter, currentCounter);
			}
		}
		return levelCounter;
	}

	private int countNodeLevel(String node) {
		int levelCounter = 0;
		for (int i = 0; i < node.length() - 1; i++) {
			if (node.charAt(i) == BACKSLASH)
				levelCounter++;
		}
		return levelCounter;
	}

	private void setTreeView() {
		this.treeScrollPane = new JScrollPane();
		this.add(treeScrollPane, BorderLayout.CENTER);
	}

	private ArrayList<String> navigateFile(File file, String rootFileName) {
		if (file.exists()) {
			File[] fileList = file.listFiles();
			for (int i = 0; i < fileList.length; i++) {
				String fileName = fileList[i].getAbsolutePath();
				int index = fileName.indexOf(BACKSLASH + rootFileName);
				String fileNameToSave = fileName.substring(index + 1);
				pathList.add(fileNameToSave);
				System.out.println(fileNameToSave);
				if (fileList[i].isDirectory()) {
					navigateFile(fileList[i], rootFileName);
				}
			}
		} else {
			System.out.println("NOT A FILE OR DIRECTORY");
		}

		return pathList;

	}

	public static void main(String[] args) {
		PrincipalView b = new PrincipalView();
	}
}
